<template>
  <div class="login_container">
    <div class="login_box">
      <!-- 头像区域 -->
      <div class="avatar">
        <img src="~/assets/images/logo.png" alt=""/>
      </div>
      <!-- 登录表单区域 -->
      <el-form
          label-width="0px"
          :model="loginForm"
          :rules="loginRules"
          class="login_form"
          ref="loginFormRef"
      >
        <!-- 用户名 -->
        <el-form-item prop="username">
          <!-- 字体文件在入口文件引入后，可以在 prefix-icon 写class名 -->
          <el-input
              v-model="loginForm.username"
              prefix-icon="iconfont icon-user"
          ></el-input>
        </el-form-item>

        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
              type="password"
              v-model="loginForm.password"
              prefix-icon="iconfont icon-3702mima"
              show-password
          ></el-input>
        </el-form-item>

        <!--验证码-->
        <el-form-item prop="verifyCode" label-width='0'>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-input v-model="loginForm.verifyCode" placeholder="验证码" @keyup.enter.native="submitForm"></el-input>
            </el-col>
            <el-col :span="12">
              <div id="v_container" style="float: right"></div>
            </el-col>
          </el-row>
        </el-form-item>

        <el-checkbox
            label="记住密码"
            v-model="loginForm.rememberMe"
            name="rememberMe"
        ></el-checkbox>


        <!-- 按钮 -->
        <el-form-item class="btns">
          <el-button type="primary" @click="login">登录</el-button>
          <el-button
              type="info"
              @click="resetLoginForm"
              title="重置表单数据、清除验证规则"
          >重置
          </el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
//导入验证码js文件
import {GVerify} from '../assets/js/verifyCode';

export default {
  name: "Login",
  data() {
    return {
      verifyCode: null,
      // 这是登录表单的数据绑定对象
      loginForm: {
        username: "",
        password: "",
        verifyCode: null,
        rememberMe: false
      },
      // 验证规则
      loginRules: {
        // 验证用户名是否合法
        username: [
          {required: true, message: "请输入用户名", trigger: "blur"},
          {
            min: 3,
            max: 16,
            message: "长度在 3 到 16 个字符",
            trigger: "blur",
          },
        ],
        // 验证密码是否合法
        password: [
          {required: true, message: "请输入登录密码", trigger: "blur"},
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur",
          },
        ],
        verifyCode: [
          {required: true, message: '请输入验证码', trigger: 'blur'}

        ]
      },
      // 消息框
      notify: null,
    };
  },
  created() {
    this.notify = this.$notify({
      title: "欢迎您",
      // message: "初始用户名：admin </br> 初始密码：123456",
      type: "success",
      dangerouslyUseHTMLString: true,
      offset: 100,
      duration: 5000,
    });
  },
  destroyed() {
    // 组件销毁时关闭提示框
    this.notify.close()
  },
  methods: {
    // 点击重置按钮，重置表单数据和验证规则
    resetLoginForm() {
      console.log(this);
      this.$refs.loginFormRef.resetFields();
    },
    submitForm() {

      // 获取验证码
      let verifyCode = this.loginForm.verifyCode
      let verifyFlag = this.verifyCode.validate(verifyCode)
      if (!verifyFlag) {
        // 验证码错误，刷新验证码
        this.refreshVerifyCode();
        this.$notify.error({
          title: '系统提示',
          message: '验证码输入错误'
        })
      }
    },
    //刷新验证码
    refreshVerifyCode() {
      // 销毁当前验证码对象
      this.verifyCode.destroyVerifyCode();
      // 初始化新的验证码对象
      this.verifyCode = new GVerify('v_container');

    },

    login() {
      console.log("勾选状态：" + this.loginForm.rememberMe)
      // 判断是否校验通过 => valid是否通过，field未通过的字段
      this.$refs.loginFormRef.validate(async (valid, field) => {
        console.log(valid, field);

        // 未通过验证
        if (!valid) {
          let arr = Object.keys(field);
          // 拿到未通过验证的验证规则提示
          return this.$message.error({
            message: field[arr[0]][0].message,
            duration: 1000,
          });
        }

        // let that = this
        // 获取验证码
        let verifyCode = this.loginForm.verifyCode
        let verifyFlag = this.verifyCode.validate(verifyCode)
        if (!verifyFlag) {
          // 验证码错误，刷新验证码
          this.refreshVerifyCode();
          this.$notify.error({
            title: '系统提示',
            message: '验证码输入错误',
          })
          return;
        }
        // else {
        //   that.$notify({
        //     title: '系统提示',
        //     message: '验证码输入正确',
        //     type: 'success'
        //   })
        // }
        this.$axios.post("/login",
            this.$qs.stringify(this.loginForm))
            .then(result => {
              console.log(result.data.data);
              //如果返回token，则跳转主页面
              if (result.data.data) {
                localStorage.setItem("access-token", result.data.data.accessToken);
                localStorage.setItem("refresh-token", result.data.data.refreshToken);
                // localStorage.setItem("token",result.data.data);
                localStorage.setItem("username", this.loginForm.username);
                this.$router.push("/home");
              } else {
                // 验证码错误，刷新验证码
                this.refreshVerifyCode();
                return this.$message.error({
                  message: result.data.message,
                  duration: 1000,
                });
              }
            });
        // let { data: result } = await this.$axios.post("login", this.$qs.stringify(this.loginForm));
        // 登录失败
        // if (result.data.code !== 200) {
        //   return this.$message.error({
        //     message: result.data.msg,
        //     duration: 1000,
        //   });
        // }

        // 登录成功
        // this.$message.success({
        //   message: "登录成功！",
        //   duration: 1000,
        // });
        // // 保存token
        // window.sessionStorage.setItem("token", result.data.token);
        // 跳转到首页
        // this.$router.push("/home");
      });
    },
  },
  mounted() {
    this.verifyCode = new GVerify('v_container')
  }
};
</script>

<style lang="less" scoped>
.login_container {
  height: 100%;
  background-color: #2b4b6b;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login_box {
  width: 450px;
  height: 350px;
  background: #fff;
  border-radius: 3px;
  position: absolute;

  .avatar {
    width: 70px;
    height: 70px;
    border: 1px solid #eee;
    border-radius: 50%;
    padding: 5px;
    position: absolute;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #fff;

    img {
      width: 70px;
      height: 70px;
      border-radius: 50%;
    }
  }
}

.login_form {
  position: absolute;
  bottom: 0;
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;
}

.btns {
  margin-top: 5px;
  display: flex;
  justify-content: center;
  //align-items: center;
  //text-align: center;
}
</style>
